<template>
  <el-card>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <el-form :inline="true" :model="searchForm" @submit.prevent>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="权限">
          <el-select v-model="searchForm.permissionType" placeholder="请选择权限" clearable style="width: 180px;">
            <el-option label="加盟员工" :value="-1" />
            <el-option label="证件收集员工" :value="0" />
            <el-option label="基础配置员工" :value="1" />
            <el-option label="开业员工" :value="2" />
            <el-option label="老店管理员工" :value="4" />
            <el-option label="团购管理员工" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="searchForm.account" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchList">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="showAddDialog = true">新增员工</el-button>
    </div>
    <el-table
      :data="employeeList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :row-key="row => row.employeeId"
      ref="tableRef"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="account" label="账号" />
      <el-table-column prop="permissionType" label="权限">
        <template #default="{ row }">
          <span>
            {{
              row.permissionType === -1
                ? '加盟员工'
                : row.permissionType === 0
                ? '证件收集员工'
                : row.permissionType === 1
                ? '基础配置员工'
                : row.permissionType === 2
                ? '开业员工'
                : row.permissionType === 4
                ? '老店管理员工'
                : row.permissionType === 5
                ? '团购管理员工'
                : row.permissionType
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag v-if="row.status === 1" type="success">正常</el-tag>
          <el-tag v-else type="info">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="{ row }">
          <el-button size="small" @click="editEmployee(row)">修改</el-button>
          <el-button size="small" type="danger" @click="deleteEmployee(row)">删除</el-button>
          <el-button size="small" :type="row.status === 1 ? 'warning' : 'success'" @click="toggleStatus(row)">
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="resetPasswordRow(row)" style="margin-left: 8px;">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 16px 0;">
      <el-button :disabled="!multipleSelection.length" @click="batchDelete">批量删除</el-button>
      <el-button :disabled="!multipleSelection.length" @click="batchToggleStatus(0)">批量禁用</el-button>
      <el-button :disabled="!multipleSelection.length" @click="batchToggleStatus(1)">批量启用</el-button>
    </div>
    <el-pagination
      v-model:current-page="pageNum"
      :page-size="pageSize"
      :total="total"
      @current-change="fetchList"
      layout="slot, prev, pager, next"
      style="margin-top: 16px;"
    >
      <template #default>
        <span style="margin-right: 16px;">总数为: {{ total }}</span>
      </template>
    </el-pagination>
    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="showAddDialog" :title="editMode ? '修改员工' : '新增员工'" width="400px" @close="resetDialog">
      <el-form :model="dialogForm" :rules="dialogRules" ref="dialogFormRef" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="dialogForm.account" placeholder="请输入账号【11位手机号码】" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="dialogForm.password" placeholder="请输入密码（数字/字母/标点符号组合）" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="dialogForm.confirmPassword" placeholder="请再次输入密码" type="password" />
        </el-form-item>
        <el-form-item label="权限" prop="permissionType">
          <el-select v-model="dialogForm.permissionType" placeholder="请选择权限">
            <el-option label="加盟员工" :value="-1" />
            <el-option label="证件收集员工" :value="0" />
            <el-option label="基础配置员工" :value="1" />
            <el-option label="开业员工" :value="2" />
            <el-option label="老店管理员工" :value="4" />
            <el-option label="团购管理员工" :value="5" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitDialog">提交</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const employeeList = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(15);
const searchForm = reactive({
  name: '',
  permissionType: '',
  account: ''
});
const multipleSelection = ref([]);
const showAddDialog = ref(false);
const editMode = ref(false);
const dialogForm = reactive({
  employeeId: '',
  name: '',
  account: '',
  password: '',
  confirmPassword: '',
  permissionType: '',
});
const passwordPattern = /^[A-Za-z0-9~!@#$%^&*()_+\-={}\[\]:;"'<>,.?/\\|`]+$/;
const dialogRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '账号必须为11位手机号码', trigger: 'blur' }
  ],
  password: [
    { validator: (rule, value, callback) => {
        if (!editMode.value) {
          if (!value) {
            callback(new Error('请输入密码'));
            return;
          }
          if (!passwordPattern.test(value)) {
          callback(new Error('密码只能包含数字、字母和基本标点符号'));
            return;
          }
        } else {
          // 编辑时可不填，填了才校验格式
          if (value && !passwordPattern.test(value)) {
            callback(new Error('密码只能包含数字、字母和基本标点符号'));
            return;
          }
        }
          callback();
      }, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: (rule, value, callback) => {
        if (!editMode.value) {
          if (!value) {
            callback(new Error('请再次输入密码'));
            return;
          }
          if (value !== dialogForm.password) {
          callback(new Error('两次输入的密码不一致'));
            return;
          }
        } else {
          // 编辑时可不填，填了才校验一致性
          if (dialogForm.password) {
            if (!value) {
              callback(new Error('请再次输入密码'));
              return;
            }
            if (value !== dialogForm.password) {
              callback(new Error('两次输入的密码不一致'));
              return;
            }
          }
        }
          callback();
      }, trigger: 'blur' }
  ],
  permissionType: [{ required: true, message: '请选择权限', trigger: 'change' }],
};
const dialogFormRef = ref();
const tableRef = ref();

function fetchList() {
  // 这里应替换为实际后端接口
  const params = new URLSearchParams({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    name: searchForm.name || '',
    permissionType: searchForm.permissionType !== '' ? searchForm.permissionType : '',
    account: searchForm.account || ''
  });
  fetch(`http://121.43.176.9:8090/api/admin/employee_list?${params.toString()}`)
    .then(r => r.json())
    .then(res => {
      if (res.code === 200) {
        employeeList.value = res.data.records;
        total.value = res.data.total;
      } else {
        employeeList.value = [];
        total.value = 0;
        ElMessage.error(res.msg || '加载失败');
      }
    })
    .catch(() => {
      employeeList.value = [];
      total.value = 0;
      ElMessage.error('加载失败');
    });
}

function resetSearch() {
  searchForm.name = '';
  searchForm.permissionType = '';
  searchForm.account = '';
  fetchList();
}

function handleSelectionChange(val) {
  multipleSelection.value = val;
}

function handlePermissionChange(row, val) {
  // 这里应调用后端接口修改权限
  fetch(`http://121.43.176.9:8090/api/employee/update`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ employeeId: row.employeeId, permissionType: val })
  })
    .then(r => r.json())
    .then(res => {
      if (res.code === 200) {
        ElMessage.success('权限已更新');
        fetchList();
      } else {
        ElMessage.error(res.msg || '更新失败');
      }
    });
}

function editEmployee(row) {
  editMode.value = true;
  Object.assign(dialogForm, row);
  dialogForm.password = '';
  dialogForm.confirmPassword = '';
  showAddDialog.value = true;
}

function deleteEmployee(row) {
  ElMessageBox.confirm('此操作将永久删除该员工，是否继续？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    fetch(`http://121.43.176.9:8090/api/admin/delete`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ employeeId: row.employeeId })
    })
      .then(r => r.json())
      .then(res => {
        if (res.code === 200) {
          ElMessage.success('删除成功');
          fetchList();
        } else {
          ElMessage.error(res.msg || '删除失败');
        }
      });
  });
}

function toggleStatus(row) {
  const newStatus = row.status === 1 ? 0 : 1;
  fetch(`http://121.43.176.9:8090/api/admin/updatePermission`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ employeeId: row.employeeId, status: newStatus })
  })
    .then(r => r.json())
    .then(res => {
      if (res.code === 200) {
        ElMessage.success('状态已更新');
        fetchList();
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
    });
}

function batchDelete() {
  if (!multipleSelection.value.length) return;
  ElMessageBox.confirm('确定要批量删除选中的员工吗？', '提示', { type: 'warning' })
    .then(() => {
      const ids = multipleSelection.value.map(i => i.employeeId);
      fetch(`http://121.43.176.9:8090/api/admin/batchDelete`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ employeeIds: ids })
      })
        .then(r => r.json())
        .then(res => {
          if (res.code === 200) {
            ElMessage.success('批量删除成功');
            fetchList();
          } else {
            ElMessage.error(res.msg || '批量删除失败');
          }
        });
    });
}

function batchToggleStatus(status) {
  if (!multipleSelection.value.length) return;
  const ids = multipleSelection.value.map(i => i.employeeId);
  fetch(`http://121.43.176.9:8090/api/admin/batchUpdateStatus`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ employeeIds: ids, status })
  })
    .then(r => r.json())
    .then(res => {
      if (res.code === 200) {
        ElMessage.success('批量操作成功');
        fetchList();
      } else {
        ElMessage.error(res.msg || '批量操作失败');
      }
    });
}

function closeDialog() {
  showAddDialog.value = false;
  resetDialog();
}

function resetDialog() {
  editMode.value = false;
  dialogForm.employeeId = '';
  dialogForm.name = '';
  dialogForm.account = '';
  dialogForm.password = '';
  dialogForm.confirmPassword = '';
  dialogForm.permissionType = '';
  if (dialogFormRef.value) dialogFormRef.value.clearValidate();
}

function submitDialog() {
  dialogFormRef.value.validate().then(() => {
    if (editMode.value) {
      // 修改
      const payload = {
        employeeId: dialogForm.employeeId,
        name: dialogForm.name,
        account: dialogForm.account,
        permissionType: dialogForm.permissionType
      };
      if (dialogForm.password) {
        payload.password = dialogForm.password;
      }
      fetch(`http://121.43.176.9:8090/api/admin/update`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      })
        .then(r => r.json())
        .then(res => {
          if (res.code === 200) {
            ElMessage.success('修改成功');
            showAddDialog.value = false;
            fetchList();
          } else {
            ElMessage.error(res.msg || '修改失败');
          }
        });
    } else {
      // 新增
      fetch(`http://121.43.176.9:8090/api/admin/add`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: dialogForm.name,
          account: dialogForm.account,
          password: dialogForm.password,
          permissionType: dialogForm.permissionType
        })
      })
        .then(r => r.json())
        .then(res => {
          if (res.code === 200) {
            ElMessage.success('新增成功');
            showAddDialog.value = false;
            fetchList();
          } else {
            ElMessage.error(res.msg || '新增失败');
          }
        });
    }
  });
}

// 行内重置密码
function resetPasswordRow(row) {
  if (!row.employeeId) return;
  ElMessageBox.confirm('此操作将重置该员工的密码，是否继续？', '重置密码确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    fetch(`http://121.43.176.9:8090/api/admin/reset_password`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ employeeId: row.employeeId })
    })
      .then(r => r.json())
      .then(res => {
        if (res.code === 200) {
          ElMessage.success('密码已重置');
        } else {
          ElMessage.error(res.msg || '重置失败');
        }
      });
  });
}

onMounted(fetchList);
</script> 